package views

import (
	"errors"
	"log"
	"net/http"
	"strconv"
	"strings"
	"study/go-blog/common"
	"study/go-blog/service"
)

func (*HTMLApi) Detail(response http.ResponseWriter, request *http.Request) {
	detailTemplate := common.Template.Detail

	path := request.URL.Path
	prefix := strings.TrimPrefix(path, "/p/")
	prefix = strings.TrimSuffix(prefix, ".html")

	pid, err := strconv.Atoi(prefix)
	if err != nil {
		detailTemplate.WriteError(response, errors.New("不识别此请求路径"))
		return
	}

	if err := request.ParseForm(); err != nil {
		log.Println("表单获取失败", err)
		detailTemplate.WriteError(response, errors.New("系统错误，请联系管理员"))
		return
	}

	postRes, err := service.GetPostDetail(pid)
	if err != nil {
		detailTemplate.WriteError(response, errors.New("查询出错"))
	}
	detailTemplate.WriteData(response, postRes)
}
